// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

//数据库服务
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  console.log(event)
  let {
    outTradeNo,
    transactionId,
  } = event
  if (event.returnCode != "SUCCESS") {
    return {
      errCode: event.returnCode,
      errMsg: event.returnMsg
    }
  }
  if (event.resultCode != "SUCCESS") {
    return {
      errCode: event.resultCode,
      errMsg: event.errCodeDes
    }
  }
  // 这里不直接更新订单状态！！！，防止虚假通知，下面采用查询微信支付服务端订单状态进行更新
  let params = {
    event,
    transactionId,
    modifyTime: Date.now()
  }
  //更新订单信息
  await db.collection('order').where({ outTradeNo: outTradeNo }).update({ data: params });

  //再次向微信支付发起查询订单，查询成功后更新db订单信息
  cloud.callFunction({
    name: 'server_Order',
    data: {
      type: 'queryOrder',
      outTradeNo,
    }
  })

  return {
    errcode: 0,
    errmsg: 'success',
    event
  }
}